package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Star;
import cn.edu.tju.elm.repository.StarRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * ClassName: StarService
 * Package: cn.edu.tju.elm.service
 * Description:
 *
 * @Author Niu Wenhang
 * @Create 2025/9/19 3:00
 * @Version 1.0
 */
@Service
@Transactional
public class StarService {
    private final StarRepository starRepository;

    public StarService(StarRepository starRepository) {
        this.starRepository = starRepository;
    }

    public Star addStar(Star star) {
        return starRepository.save(star);
    }

    public List<Star> getStarsByUserId(Long userId) {
        return starRepository.findByUserIdAndDeletedFalse(userId);
    }

    public Optional<Star> getStarById(Long id) {
        return starRepository.findById(id);
    }

    public Star updateStar(Star star) {
        return starRepository.save(star);
    }

    public void deleteStar(Long id) {
        starRepository.deleteById(id);
    }

    public Optional<Star> getStarByUserIdAndBusinessId(Long userId, Long businessId) {
        return starRepository.findByUserIdAndBusinessIdAndDeletedFalse(userId, businessId);
    }

    public boolean checkStarExists(Long userId, Long businessId) {
        return starRepository.existsByUserIdAndBusinessIdAndDeletedFalse(userId, businessId);
    }

    public List<Star> getRecentStarsByUserId(Long userId, Integer limit) {
        return starRepository.findByUserIdAndDeletedFalse(userId).stream()
                .sorted((s1, s2) -> s2.getCreateTime().compareTo(s1.getCreateTime()))
                .limit(limit)
                .collect(java.util.stream.Collectors.toList());
    }

    public Long getStarCountByUserId(Long userId) {
        return starRepository.countByUserIdAndDeletedFalse(userId);
    }
}
